﻿#ifndef STL_TIMER_IMP_20220103_H
#define STL_TIMER_IMP_20220103_H

#include <event2/event.h>
#include <event2/event_struct.h>
#include <stdint.h>
#include <atomic>
#include <chrono>
#include <mutex>
#include <atomic>
#include <deque>
#include "SLT_timer.h"
typedef	void (*SLT_libeventTimerTimeOut)(SLT_timer_CallBackType _type, SLT_TIMER_HANDLE timerid, void* userData);

class LibeventTimer;
class LibEventTimerContext {
public:
	LibEventTimerContext() :to_cancel(false) {}
	bool to_cancel;
	uint64_t timerid;
	bool periodic;
	void* prama;
	uint32_t msgid;
	event m_ev;
	SLT_libeventTimerTimeOut cb;
	LibeventTimer* pTimer;

	timeval etime;
};

class LibeventTimer{
public:
    LibeventTimer()
    {
        m_base = nullptr;
        m_running = false;
        m_timerid_seed = 1;
    }

    static void init();
    bool start();

    //没有到期的定时器将会被回调
    //void stop();

    //返回timerid, 返回0表示失败
    //单位 毫秒
    int set_timer(uint64_t& _th,uint32_t elapseMs, bool periodic, SLT_libeventTimerTimeOut cb, void* prama);
    bool cancle(uint64_t timerid);

    void loop_proc(void*);
    void _setTimer_cb(evutil_socket_t fd, short event);
public:
    std::mutex m_baseLock;
    event_base* m_base = nullptr;
    bool m_running = false;


	std::deque<LibEventTimerContext*>  m_setTimerlist;
    std::deque<LibEventTimerContext*>  m_listtemp;
	evutil_socket_t pair[2];
    bool m_setRun = false;

    std::atomic<uint64_t> m_timerid_seed;
};

#endif